package com.lgmshare.k3.ui.base;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.lgmshare.component.utils.FileUtils;
import com.lgmshare.component.utils.ImageUtils;
import com.lgmshare.component.utils.UIUtils;
import com.lgmshare.k3.helper.ExecuteAsyncTaskHelper;
import com.lgmshare.k3.helper.PathConfigurationHelper;
import com.lgmshare.k3.helper.concurrency.Command;
import com.lgmshare.k3.helper.concurrency.CommandCallback;
import com.lgmshare.k3.ui.dialog.ActionSheetDialog;

import java.io.File;
import java.io.IOException;

/**
 * @author lim
 * @description: TODO
 * @email lgmshare@gmail.com
 * @datetime 2017/4/19 17:45
 */
public abstract class BaseImageSelectActivity extends BaseActivity {

    private static final int REQ_PERMISSIONS_CAMERA = 10;
    private static final int REQ_PERMISSIONS_STORAGE = 11;

    private static final int REQ_RESULT_PHOTO_CODE = 1530;
    private static final int REQ_RESULT_CAPTURE_CODE = 1531;
    private static final int REQ_RESULT_CORP_CODE = 1532;

    private static final String POSTFIX = ".jpeg";

    private String mSaveImagePath;// 图片保存路径
    private String mCropImagePath;//
    private String mTempImagePath;// 照相机缓存路径
    private boolean mCrop = false;// 是否需要裁剪

    private ActionSheetDialog mActionSheetDialog;

    protected void callImageSelect() {
        String filePath = PathConfigurationHelper.getFilePathOfExternal(this, "temp", POSTFIX);
        callImageSelect(filePath, true);
    }

    /**
     * 调起图片选择弹窗
     *
     * @param filePath 图片保存路劲
     */
    protected void callImageSelect(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            throw new NullPointerException("imageFile save to path is null");
        }
        callImageSelect(filePath, true);
    }

    /**
     * 调起图片选择弹窗
     *
     * @param filePath 图片保存路径
     * @param crop     是否需要裁减
     */
    protected void callImageSelect(String filePath, boolean crop) {
        mCrop = crop;
        mSaveImagePath = filePath;
        mTempImagePath = PathConfigurationHelper.getFilePathOfExternal(this, "image_capture_temp", POSTFIX);
        mCropImagePath = PathConfigurationHelper.getFilePathOfExternal(this, "image_capture_crop", POSTFIX);

        FileUtils.createFile(mSaveImagePath);
        FileUtils.createFile(mCropImagePath);
        FileUtils.createFile(mTempImagePath);
        showSelectDialog();
    }

    private void showSelectDialog() {
        if (mActionSheetDialog == null) {
            mActionSheetDialog = new ActionSheetDialog(this);
            mActionSheetDialog.addSheetItem("拍照", new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int position) {
                    checkRequestPermission(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionCheckCallback() {
                        @Override
                        public void onPermissionsGranted(String[] permissions) {
                            openCamera();
                        }

                        @Override
                        public void onPermissionDenied(String[] permissions) {

                        }

                    });
                }
            });
            mActionSheetDialog.addSheetItem("从手机相册选择", new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int position) {
                    checkRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, new PermissionCheckCallback() {

                        @Override
                        public void onPermissionsGranted(String[] permissions) {
                            openMediaStore();
                        }

                        @Override
                        public void onPermissionDenied(String[] permissions) {

                        }
                    });
                }
            });
        }
        mActionSheetDialog.show();
    }

    /**
     * 打开手机相册
     */
    private void openMediaStore() {
        if (!android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            showToast("存储卡已取出，手机相册暂不可用");
            return;
        }
        Intent intent = new Intent(); // 开启Pictures画面Type设定为image
        intent.setType("image/*"); // 使用Intent.ACTION_GET_CONTENT这个Action
        intent.setAction(Intent.ACTION_GET_CONTENT);  //取得相片后返回本画面
        startActivityForResult(intent, REQ_RESULT_PHOTO_CODE);
    }

    /**
     * 打开照相机
     */
    private void openCamera() {
        if (!android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            showToast("存储卡已取出，拍照功能暂不可用");
            return;
        }
        Uri imageUri = FileUtils.getUri(getActivity(), mTempImagePath);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, REQ_RESULT_CAPTURE_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_RESULT_PHOTO_CODE) {
            if (resultCode == RESULT_OK) {
                crop(data.getData());
            }
        } else if (requestCode == REQ_RESULT_CAPTURE_CODE) {
            if (resultCode == RESULT_OK) {
                crop(FileUtils.getUri(getActivity(), mTempImagePath));
            }
        } else if (requestCode == REQ_RESULT_CORP_CODE) {
            if (resultCode == RESULT_OK) {
                compress(mCropImagePath);
            }
        }
    }

    /**
     * 图片裁剪
     *
     * @param imageUri
     */
    private void crop(Uri imageUri) {
        if (imageUri != null) {
            compress(FileUtils.getPath(getActivity(), imageUri));
        }
    }

    /**
     * 图片压缩
     *
     * @param filePath
     */
    private void compress(final String filePath) {
        ExecuteAsyncTaskHelper.execute(getActivity(), "", new Command<Integer>() {
            @Override
            public void start(final CommandCallback<Integer> callback) {
                UIUtils.runOnAsyncThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            File file = new File(filePath);
                            ImageUtils.compress(file, 480, 800, Bitmap.CompressFormat.JPEG, 70, mSaveImagePath);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        UIUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                callback.onResult(0);
                                onImageSelectResult(mSaveImagePath);
                            }
                        });
                    }
                });
            }
        });
    }

    /**
     * 返回选择的图片
     *
     * @param saveImagePath
     */
    protected abstract void onImageSelectResult(String saveImagePath);

}
